<?php
namespace Admin\Controller;

use Think\Controller;

class WechatController extends Controller{
    
    public function wechat()
    {
        define('TOKEN', 'crazycat');
        
        $echoStr = $_GET["echostr"];
        if (!empty($echoStr)){  // 验证
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        }
        $this->responseMsg(); // 回复消息
        
    }
    
    // 发送信息
    public function responseMsg()
    {
        // 获取微信服务器发过来的xml数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            libxml_disable_entity_loader(true);//安全防护
            
            // 加载xml数据
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName; // 发送消息的用户名
            $toUsername = $postObj->ToUserName;  // 接收消息的用户名
            $createTime = $postObj->CreateTime;  // 消息发送时间
            $msgType = $postObj->MsgType;   // 获取用户发送内容的数据类型
            $content = $postObj->Content;  // 获取用户发送的内容
            $msgId = $postObj->MsgId;
            
            
            if($msgType == 'text'){ // 回复用户
                
                // 查找博客
                $res = M('blog')->where(array('title'=>array('like','%'.$content.'%')))->select();
                if (count($res) != 0){ // 能查到数据
                    $content = array();
                    foreach ($res as $k=>$v){
                        $content[$k]['title'] = $v['title'];
                        $content[$k]['description'] = $v['description'];
                        $content[$k]['picurl'] = 'http://'.$_SERVER['HTTP_HOST'].$v['theme'];
                        $content[$k]['url'] = U('Home/BlogDetails/index',array('blog_id'=>$v['id']),true,true);
                    }
                    echo $this->sendMessage($toUsername, $fromUsername, 'news', $content);
                }else{ // 不能查到数据
                    echo $this->sendMessage($toUsername, $fromUsername, 'text', '未查询到相关博客数据');
                }
            }elseif($msgType == 'event'){ // 菜单点击事件
                
                
                
                $event = $postObj->Event;  // 获取事件的类型
                
                if ($event== 'subscribe'){// 关注订阅号
                    echo $this->sendMessage($toUsername, $fromUsername, 'text', '欢迎关注订阅号');
                }elseif($event == 'CLICK'){ // 点击自定义菜单回复
                    $key = $postObj->EventKey;
                    $content = M('caidan')->where(array('key'=>$key))->getField('content');
                    echo $this->sendMessage($toUsername, $fromUsername, 'text', $content);
                }else{
                    file_put_contents('./log.txt','1234567');
                    echo $this->sendMessage($toUsername, $fromUsername, 'text', '1234567');
                }
                
            }else{
                $contentStr = "您发的消息类型不是文本。而是".$content;
                echo $this->sendMessage($toUsername, $fromUsername, 'text', $contentStr);
                
            }
            
        }
    }
    
    // 发送消息给微信用户
    private function sendMessage($fromUsername,$toUsername,$type,$content){
        $returnXml = '<xml>';
        $returnXml .= '<ToUserName><![CDATA['.$toUsername.']]></ToUserName>';
        $returnXml .= '<FromUserName><![CDATA['.$fromUsername.']]></FromUserName>';
        $returnXml .= '<CreateTime>'.time().'</CreateTime>';
        $returnXml .= '<MsgType><![CDATA['.$type.']]></MsgType>';
        if ($type == 'news'){ // 发送图文信息
            
            $returnXml .= $this->sendNews($content);
        }else if($type == 'text'){ // 发送文字信息
            $returnXml .= '<Content><![CDATA['.$content.']]></Content>';
        }
        $returnXml .= '</xml>';
        return $returnXml;
    }
    
    // 发送图文信息
    private function sendNews($content){
        $returnXml = '<ArticleCount>'.count($content).'</ArticleCount>';
        $returnXml .= '<Articles>';
        foreach ($content as $v){
            $returnXml .= '<item>';
            $returnXml .= '<Title><![CDATA['.$v['title'].']]></Title> ';
            $returnXml .= '<Description><![CDATA['.$v['description'].']]></Description>';
            $returnXml .= '<PicUrl><![CDATA['.$v['picurl'].']]></PicUrl>';
            $returnXml .= '<Url><![CDATA['.$v['url'].']]></Url>';
            $returnXml .= '</item>';
        }
        $returnXml .= '</Articles>';
        return $returnXml;
    }
    
    // 验证微信
    private function checkSignature()
    {
        if (!defined("TOKEN")) {
            return false;
        }
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}